<template>
  <div class="theme-examples-controls">
    <div class="example-container">
      <label class="color-select">
        <select id="themeSelect">
          <option value="ht-theme-main">Main Light</option>
          <option value="ht-theme-horizon">Horizon Light</option>
          <option value="ht-theme-main-dark">Main Dark</option>
          <option value="ht-theme-horizon-dark">Horizon Dark</option>
          <option value="ht-no-theme">No theme</option>
        </select>
        <div id="colorBox" class="color-box">
          <span class="color" style="background: var(--ht-foreground-color);"></span>
          <span class="color" style="background: var(--ht-background-color);"></span>
          <span class="color" style="background: var(--ht-accent-color);"></span>
        </div>
      </label>
    </div>
  </div>
  <div id="exampleTheme" class="disable-auto-theme"></div>
</template>

<script setup lang="ts">
import Handsontable from "handsontable";
import "handsontable/styles/handsontable.css";
import "handsontable/styles/ht-theme-main.css";
import "handsontable/styles/ht-theme-horizon.css";
import { data } from "./data";
import { onMounted, ref, reactive } from "vue";
import { registerAllModules } from 'handsontable/registry';
import { h } from 'vue';
registerAllModules();

// 如果上述配置不起作用，可以通过自定义表头渲染器来实现
const headerRenderer = (instance, TD, row, col, prop, value) => {
  TD.innerHTML = '操作';
  TD.style.textAlign = 'center';
  // 移除表头的点击事件和菜单相关的类
  TD.className = TD.className.replace('columnSorting', '').replace('htNoWrap', '');
  return TD;
};

// 存储选中状态
const selectedRows = ref(new Set());
const isAllSelected = ref(false);
onMounted(() => {
  const example = document.getElementById("exampleTheme");
  const hotInstance = new Handsontable(example as Element, {
    data,
    width: "100%",
    height: 450,
    colWidths: [100, 270, 280, 220, 240, 220, 220, 220, 140],
    colHeaders: [
      "Company Name",
      "Name",
      "Sell date",
      "In stock",
      "Quantity",
      "Order ID",
      "Country",
    ],
    contextMenu: [
      "cut",
      "copy",
      "---------",
      "row_above",
      "row_below",
      "remove_row",
      "---------",
      "alignment",
      "make_read_only",
      "clear_column",
    ],
    columns: [
      {
        title: 'all',
        renderer: checkboxRenderer,
        readOnly: true,
      },
      {
        // 新增行号列配置
        renderer: (instance, td, row) => {
          td.innerHTML = (row + 1).toString();
          td.style.textAlign = 'center';
          return td;
        },
        readOnly: true,
        title: '行号'
      },
      {
        data: 1,
        type: "text",
        headerClassName: "htLeft",
      },
      {
        data: 3,
        type: "text",
        headerClassName: "htLeft",
      },
      {
        data: 4,
        type: "date",
        allowInvalid: false,
        dateFormat: "DD/MM/YYYY",
        headerClassName: "htLeft",
      },
      {
        data: 6,
        type: "checkbox",
        className: "htCenter",
        headerClassName: "htLeft",
      },
      {
        data: 7,
        type: "numeric",
        headerClassName: "htLeft",
      },
      {
        data: 5,
        type: "text",
        headerClassName: "htLeft",
      },
      {
        data: 2,
        type: "text",
        headerClassName: "htLeft",
      },
      {
        title: '操作',
        renderer: actionRenderer,
        readOnly: true, // 设置为只读，防止编辑
        width: 150, // 设置列宽
        fixed: true,
        dropdownMenu: false,

        headerRenderer: headerRenderer, // 添加自定义表头渲染器c
      }
    ],
    // 添加单元格渲染后的回调
    afterRenderer: (TD, row, col, prop, value, cellProperties) => {
      if (selectedRows.value.has(row)) {
        TD.classList.add('selected-row');
      } else {
        TD.classList.remove('selected-row');
      }
    },
    manualColumnMove: true,
    manualColumnFreeze: true,
    dropdownMenu: true,

    hiddenColumns: {
      indicators: true,
    },
    multiColumnSorting: true,
    filters: true,
    rowHeaders: false,
    manualRowMove: true,
    headerClassName: "htLeft",
    autoWrapRow: true,
    autoWrapCol: true,
    manualRowResize: true,
    manualColumnResize: true,
    navigableHeaders: true,
    licenseKey: "non-commercial-and-evaluation",
  });
  const colorBox = document.getElementById('colorBox')!;
  const themeSelect = document.getElementById('themeSelect')!;
  const currentTheme = document
    .querySelector('html')
    ?.classList.contains('theme-dark')
    ? 'ht-theme-horizon-dark'
    : 'ht-theme-horizon';

  const setTheme = (theme: string) => {
    colorBox.classList.value = `color-box ${theme}`;
    hotInstance.useTheme(theme);
    hotInstance.render();
  };

  (themeSelect as HTMLSelectElement).value = currentTheme;
  setTheme(currentTheme);

  themeSelect.addEventListener('change', (event) => {
    const themeName = (event.target as HTMLSelectElement).value;

    setTheme(themeName);
  });

});


const actionRenderer = (instance, td, row, col, prop, value, cellProperties) => {
  td.innerHTML = '';
  td.className = 'action-column'; // 添加类名
  // 阻止容器的点击事件传播
  const container = document.createElement('div');
  container.className = 'action-container';
  container.addEventListener('mousedown', (e) => {
    e.stopPropagation();
  });
  const detailBtn = document.createElement('button');
  detailBtn.innerHTML = '详情';
  detailBtn.className = 'btn-detail';
  detailBtn.onmousedown = (e) => {
    e.stopPropagation(); // 阻止事件冒泡
    e.preventDefault(); // 阻止默认行为
  };
  detailBtn.onclick = (e) => {
    e.stopPropagation();
    handleDetail(instance.getSourceDataAtRow(row));
  };

  const deleteBtn = document.createElement('button');
  deleteBtn.innerHTML = '删除';
  deleteBtn.className = 'btn-delete';
  deleteBtn.onclick = (e) => {
    e.stopPropagation();
    handleDelete(instance.getSourceDataAtRow(row));
  };

  td.appendChild(detailBtn);
  td.appendChild(deleteBtn);

  return td;
};

// 复选框渲染器
const checkboxRenderer = (instance, td, row, col, prop, value, cellProperties) => {
  td.innerHTML = '';

  const checkbox = document.createElement('input');
  checkbox.type = 'checkbox';
  checkbox.checked = selectedRows.value.has(row);

  // 如果是表头，则作为全选框
  if (row === -1) {
    checkbox.checked = isAllSelected.value;
    checkbox.onclick = (e) => {
      e.stopPropagation();
      isAllSelected.value = checkbox.checked;
      if (checkbox.checked) {
        // 全选
        const totalRows = instance.countRows();
        for (let i = 0; i < totalRows; i++) {
          selectedRows.value.add(i);
        }
      } else {
        // 取消全选
        selectedRows.value.clear();
      }
      instance.render(); // 重新渲染表格
    };
  } else {
    // 行选择框
    checkbox.onclick = (e) => {
      e.stopPropagation();
      if (checkbox.checked) {
        selectedRows.value.add(row);
      } else {
        selectedRows.value.delete(row);
      }
      // 更新全选状态
      isAllSelected.value = selectedRows.value.size === instance.countRows();
      instance.render(); // 重新渲染表格
    };
  }

  td.appendChild(checkbox);
  return td;
};



// 获取选中的行数据
const getSelectedRowsData = () => {
  const selectedData = Array.from(selectedRows.value).map(rowIndex => data.value[rowIndex]);
  console.log('选中的数据:', selectedData);
  return selectedData;
};

// 处理详情点击
const handleDetail = (rowData: any) => {
  console.log('查看详情:', rowData);
  // 实现你的详情查看逻辑
};

// 处理删除点击
const handleDelete = (rowData: any) => {
  console.log('删除行:', rowData);
  // 实现你的删除逻辑
};

</script>

<style scoped>
/* 按钮样式 */
:deep(.btn-detail) {
  margin-right: 8px;
  padding: 2px 8px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

:deep(.btn-delete) {
  padding: 2px 8px;
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

/* 固定最后一列 */
:deep(.action-column) {
  position: sticky !important;
  right: 0;
  background-color: white !important;
  box-shadow: -2px 0 5px rgba(0, 0, 0, 0.1);
  z-index: 2;
}

/* 固定表头的操作列 */
:deep(.handsontable .htCore th:last-child) {
  position: sticky !important;
  right: 0;
  background-color: white !important;
  box-shadow: -2px 0 5px rgba(0, 0, 0, 0.1);
  z-index: 3;
}

:deep(.btn-detail) {
  margin-right: 8px;
  padding: 2px 8px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

:deep(.btn-delete) {
  padding: 2px 8px;
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

:deep(.btn-detail:hover) {
  background-color: #40a9ff;
}

:deep(.btn-delete:hover) {
  background-color: #ff7875;
}

/* 选中行的样式 */
:deep(.selected-row) {
  background-color: #e6f7ff !important;
}

/* 选中行的hover效果 */
:deep(.selected-row:hover) {
  background-color: #bae7ff !important;
}

/* 复选框单元格的样式 */
:deep(.handsontable td:first-child) {
  cursor: pointer;
}

/* 确保操作列在选中状态下保持白色背景 */
:deep(.action-column.selected-row) {
  background-color: white !important;
}
</style>
